package com.kaifamiao.wendao.filter;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Level;
import com.kaifamiao.wendao.service.LevelService;
import com.kaifamiao.wendao.utils.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Set;

public class LTimeFilter implements Filter {
    private Set<String> urls;
    private LevelService levelService=new LevelService();

    @Override
    public void init(FilterConfig config) throws ServletException {
        urls = Set.of("/topic/list/out");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session=request.getSession();
        String uri = request.getRequestURI();
        // 确定当前被访问的资源是否属于需要被拦截
        if (urls.contains(uri)) {
            Object o= session.getAttribute(Constants.CUSTOMER_LOGINED);
            Customer customer=(Customer) o;
            Level level= levelService.find(customer.getId());
            level.setLogin_time(level.getLogin_time()+1);
             levelService.update(level);
            response.sendRedirect(request.getContextPath() + "/topic/list");

        }

        // 继续向后传递请求和响应对象
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    }
}